package auth

import (
	"context"
	"database/sql"
	v1 "gf-admin-api-template/api/v1"
	"gf-admin-api-template/internal/consts"
	"gf-admin-api-template/internal/model"
	"gf-admin-api-template/internal/service"
	"gf-admin-api-template/internal/utils/lerr"
	"golang.org/x/crypto/bcrypt"
)

type sAuth struct{}

func init() {
	service.RegisterAuth(New())
}

func New() *sAuth {
	return &sAuth{}
}

func (a *sAuth) CheckHeardKey(ctx context.Context, key string) (res *model.UserInfo, err error) {
	res, err = service.User().GetCacheUser(ctx, key)
	return
}

func (a *sAuth) LoginCheck(ctx context.Context, req *v1.LoginReq) (res *model.UserInfo, err error) {
	res, err = service.User().FindByAccount(ctx, req.Account)
	if err != nil {
		if err == sql.ErrNoRows {
			err = lerr.Fail(lerr.Lerr{Msg: "账号或密码错误"})
		}
		return
	}
	err = bcrypt.CompareHashAndPassword([]byte(res.Password), []byte(req.Password))
	if err != nil {
		if err == bcrypt.ErrMismatchedHashAndPassword {
			err = lerr.Fail(lerr.Lerr{Msg: "账号或密码错误"})
		}
	}
	return
}

func (a *sAuth) GetUser(ctx context.Context) (user *model.UserInfo) {
	return ctx.Value("user").(*model.UserInfo)
}

func (a *sAuth) IsAdmin(ctx context.Context) bool {
	user := a.GetUser(ctx)
	if user.Id == consts.UserAdminId {
		return true
	}
	for _, role := range user.Roles {
		if role.Id == consts.RoleAdminId {
			return true
		}
	}
	return false
}
